package com.example.guiguiapplicatio.fragment.followup;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.icu.util.Calendar;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.databinding.FragmentFollowUpReportBinding;
import com.example.guiguiapplicatio.databindingBean.followup.ListFollowupWith;
import com.example.guiguiapplicatio.fragment.followup.adapter.FollowUpReportFragmentAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class FollowUpReportFragment extends Fragment {
    private FragmentFollowUpReportBinding binding;
    private FollowUpReportFragmentAdapter adapter;
    private Api api;
    private Retrofit retrofit;
    private OkHttpClient client;
    private Integer PARAM_PAGE_BEGIN = 0;
    private Integer PARAM_PAGE_SIZE = 10;
    private String PARAM_TIME_LIMIT = null;
    private String PARAM_DATEA = null, PARAM_DATEB = null;
    private Integer PARAM_STATE = 3;
    private String PARAM_TYPE = null;
    private String PARAM_SEARCH_STRING = null;
    private List<ListFollowupWith> NOW_DATA = new ArrayList<>();
    private Call<ResponseBody<List<ListFollowupWith>>> call;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PARAM_SEARCH_STRING = getArguments().getString("idcard");
        PARAM_TYPE = getArguments().getString("type");

        client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .baseUrl(getString(R.string.api))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentFollowUpReportBinding.inflate(inflater, container, false);
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        binding.recy.setLayoutManager(new LinearLayoutManager(binding.getRoot().getContext()));
        setReflashAndLoadMore();
        setTimeSearch();
        initData();
        return binding.getRoot();
    }

    private void setTimeSearch() {

        binding.timeStart.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month = month + 1;
                        String str = year + "年" + month + "月" + dayOfMonth + "日";//把日期变成字符串格式显示出来
                        binding.timeStart.setText(str);//文本框显示的内容设置成经过逻辑处理后的日期
                    }
                };
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(getContext(), 5, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        binding.timeFinish.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month = month + 1;
                        String str = year + "年" + month + "月" + dayOfMonth + "日";//把日期变成字符串格式显示出来
                        binding.timeFinish.setText(str);//文本框显示的内容设置成经过逻辑处理后的日期
                    }
                };
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(getContext(), 5, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();

            }
        });
        binding.clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.timeStart.setText("");
                binding.timeFinish.setText("");
                PARAM_DATEA = null;
                PARAM_DATEB = null;
            }
        });

        binding.beganSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (binding.timeFinish.getText().length() > 0 && binding.timeStart.getText().length() > 0)
//                {
                PARAM_DATEA = String.valueOf(binding.timeStart.getText());
                PARAM_DATEB = String.valueOf(binding.timeFinish.getText());
                Log.e("onClick", "onClick: PARAM_DATEA  PARAM_DATEB" + PARAM_DATEA + PARAM_DATEB);
                PARAM_TIME_LIMIT = "自定义";
                PARAM_PAGE_BEGIN = 0;
                call = api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                call.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                        ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                        if (responseBody != null) {
                            NOW_DATA.clear();
                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA.add(responseBody.getData().get(i));
                            }
                            adapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                        if (getContext() != null) {
                            Toast.makeText(getContext(), "网络连接有误,获取拉数据失败", Toast.LENGTH_LONG).show();
                        }
                    }
                });
//                }else {
//                    Toast.makeText(getContext(), "请输入完整的两个时间", Toast.LENGTH_LONG).show();
//                }


            }
        });

    }

    private void setReflashAndLoadMore() {
        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishRefresh(600);
                PARAM_PAGE_BEGIN = 0;
                PARAM_TIME_LIMIT = null;
                call = api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                call.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                        ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                        if (responseBody != null) {
                            NOW_DATA.clear();
                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA.add(responseBody.getData().get(i));
                            }
                            binding.refreshLayout.finishRefresh(true);
                            adapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                        if (getContext() != null) {
                            binding.refreshLayout.finishRefresh(false);
                            Toast.makeText(getContext(), "网络连接有误,获取拉数据失败", Toast.LENGTH_LONG).show();
                        }
                    }
                });

            }
        });

        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishLoadMore(600);
                PARAM_PAGE_BEGIN = NOW_DATA.size();
                PARAM_TIME_LIMIT = null;
                call = api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                call.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                        ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                        if (responseBody != null) {
                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA.add(responseBody.getData().get(i));
                            }
                            binding.refreshLayout.finishLoadMore(true);
                            adapter.notifyDataSetChanged();

                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                        if (getContext() != null) {
                            binding.refreshLayout.finishLoadMore(false);
                            Toast.makeText(getContext(), "网络连接有误,获取拉数据失败", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
    }

    private void initData() {
        binding.servicTitle.setText(PARAM_TYPE);
        PARAM_TIME_LIMIT = null;
        call = api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);

        adapter = new FollowUpReportFragmentAdapter(NOW_DATA, PARAM_TYPE);
        binding.recy.setAdapter(adapter);
        call.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
            @Override
            public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                if (responseBody != null) {
                    NOW_DATA.clear();
                    for (int i = 0; i < responseBody.getData().size(); i++) {
                        Gson gson=new Gson();
                        Log.e(" adapter.notifyDataSetChanged();: ", " adapter.onResponse();查看刷新效率: "+gson.toJson(responseBody.getData()));
                        NOW_DATA.add(responseBody.getData().get(i));
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                if (getContext() != null) {
                    Toast.makeText(getContext(), "网络连接有误,获取拉数据失败", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }
}